<template>
  <div class="home">
    <h1>功能示例</h1>
    <v-icon name="success" color="#ee0a24" size="24" />

    <!-- 路由跳转示例 -->
    <section class="section">
      <h2>路由跳转示例</h2>
      <div class="button-group">
        <van-button type="primary" @click="handleNavigate('/about')">
          跳转到关于页面
        </van-button>
        <van-button type="info" @click="handleNavigateWithQuery">
          带参数跳转
        </van-button>
        <van-button type="warning" @click="handleReplace">
          替换当前页面
        </van-button>
      </div>
    </section>

    <!-- 自定义指令示例 -->
    <section class="section">
      <h2>自定义指令示例</h2>
      <div class="button-group">
        <van-button type="primary" v-debounce:500="handleDebounceClick">
          防抖按钮 (500ms)
        </van-button>

        <van-button type="info" v-throttle="handleThrottleClick">
          节流按钮 (默认300ms)
        </van-button>
      </div>
    </section>

    <!-- Pinia 状态管理示例 -->
    <section class="section">
      <h2>状态管理示例</h2>
      <div class="card">
        <van-button type="primary" @click="counter.increment">
          count is {{ counter.count }}
        </van-button>
      </div>
    </section>

    <!-- Loading 组件示例 -->
    <section class="section">
      <h2>Loading 示例</h2>
      <van-button type="primary" @click="showLoading">
        显示 Loading 2秒
      </van-button>
    </section>

    <!-- 动态表单示例 -->
    <section class="section">
      <h2>动态表单示例</h2>
      <dynamic-form
        ref="formRef"
        v-model="formData"
        :config="formConfig"
        submit-text="提交表单"
        @submit="handleFormSubmit"
        @validate="handleValidate"
      />
    </section>
  </div>
</template>

<script setup>
import { ref, h } from "vue";
import { useRouter } from "vue-router";
import { useCounterStore } from "../store/counter";
import { getCurrentInstance } from "vue";
import { showToast, Rate } from "vant";
import DynamicForm from "../components/DynamicForm.vue";
import VIcon from "../components/VIcon.vue";

const router = useRouter();
const counter = useCounterStore();
const { proxy } = getCurrentInstance();

// 路由跳转相关方法
const handleNavigate = (path) => {
  router.push(path);
};

const handleNavigateWithQuery = () => {
  router.push({
    path: "/about",
    query: { from: "home", timestamp: Date.now() },
  });
};

const handleReplace = () => {
  router.replace("/about");
};

// Loading 控制
const showLoading = () => {
  proxy.$loading.show();
  setTimeout(() => {
    proxy.$loading.hide();
  }, 2000);
};

// 防抖节流示例方法
const handleDebounceClick = () => {
  showToast("触发防抖点击");
};

const handleThrottleClick = () => {
  showToast("触发节流点击");
};

// 表单相关
const formData = ref({});
const formRef = ref(null);

const formConfig = [
  {
    type: "input",
    prop: "username",
    label: "用户名",
    placeholder: "请输入用户名",
    rules: [
      { required: true, message: "请填写用户名" },
      {
        pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{2,20}$/,
        message: "用户名格式不正确",
      },
    ],
  },
  {
    type: "radio",
    prop: "gender",
    label: "性别",
    defaultValue: "male",
    options: [
      { label: "男", value: "male" },
      { label: "女", value: "female" },
    ],
    rules: [{ required: true, message: "请选择性别" }],
  },
  {
    type: "select",
    prop: "city",
    label: "城市",
    placeholder: "请选择城市",
    options: [
      { label: "北京", value: "beijing" },
      { label: "上海", value: "shanghai" },
      { label: "广州", value: "guangzhou" },
    ],
    rules: [{ required: true, message: "请选择城市" }],
  },
  {
    type: "checkbox",
    prop: "interests",
    label: "兴趣爱好",
    options: [
      { label: "阅读", value: "reading" },
      { label: "音乐", value: "music" },
      { label: "运动", value: "sports" },
      { label: "旅行", value: "travel" },
      { label: "美食", value: "food" },
    ],
    rules: [{ required: true, message: "请选择兴趣爱好" }],
  },
  {
    type: "textarea",
    prop: "description",
    label: "个人简介",
    rows: 3,
    maxlength: 200,
    showWordLimit: true,
    rules: [{ required: true, message: "请填写个人简介" }],
  },
  {
    type: "custom",
    prop: "customField",
    label: "自定义组件",
    defaultValue: "",
    render: (props) =>
      h("div", {
        class: "custom-component",
        innerHTML: `当前值：${props.modelValue || "未设置"}`,
        onClick: () => {
          if (typeof props["onUpdate:modelValue"] === "function") {
            props["onUpdate:modelValue"]("新值" + Date.now());
          }
        },
      }),
    rules: [{ required: true, message: "请选择值" }],
  },
  {
    type: "custom",
    prop: "rate",
    label: "评分",
    defaultValue: 0,
    render: (props) =>
      h(Rate, {
        modelValue: Number(props.modelValue || 0),
        "onUpdate:modelValue": (val) => {
          if (typeof props["onUpdate:modelValue"] === "function") {
            props["onUpdate:modelValue"](val);
          }
        },
        count: 5,
        size: 25,
        color: "#ffd21e",
        voidColor: "#eee",
      }),
    rules: [{ required: true, message: "请评分" }],
  },
]; // 数组结束

const handleFormSubmit = async (data) => {
  try {
    proxy.$loading.show();
    // 模拟API请求
    await new Promise((resolve) => setTimeout(resolve, 1000));
    console.log("提交的表单数据：", data);
    showToast("提交成功");
  } catch (error) {
    showToast("提交失败");
  } finally {
    proxy.$loading.hide();
  }
};

const handleValidate = (isValid) => {
  console.log("表单验证结果：", isValid);
};

// 手动验证表单方法
// eslint-disable-next-line no-unused-vars
const validateForm = async () => {
  const isValid = await formRef.value?.validate();
  return isValid;
};
</script>

<style scoped>
.home {
  padding: 10px; /* 减少整体页面的内边距 */
}

.section {
  margin-bottom: 20px; /* 减少每个部分之间的间距 */
  padding: 15px; /* 减少每个部分的内边距 */
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 调整阴影使其更柔和 */
}

h1 {
  margin-bottom: 20px; /* 减少标题的下边距 */
  color: #323233;
  font-size: 24px;
}

h2 {
  margin-bottom: 15px; /* 减少副标题的下边距 */
  color: #323233;
  font-size: 18px;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 减少按钮之间的间距 */
  justify-content: center;
}

.card {
  margin: 12px 0; /* 减少卡片的上下边距 */
}

:deep(.van-button) {
  margin: 0 6px; /* 减少按钮的左右边距 */
}

:deep(.van-cell-group) {
  margin-bottom: 12px; /* 减少单元格组的下边距 */
}

.custom-component {
  padding: 8px; /* 减少自定义组件的内边距 */
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
}
</style>
